package com.lsy.poi;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.lsy.poi.exception.workbook.NoSuchSheetException;
import com.lsy.poi.sheet.SheetParser;
import com.swa99ylum.pxp.a.a009.Test1;

public class PluggableFileParser extends Parser {
	
	private static Logger logger = Logger.getLogger(PluggableFileParser.class);
	
	/**
	 * workbook 应该不需要 validators 吧
	 */
	private XSSFWorkbook workbook;
	private SheetParser[] sheetParsers;
	
	
	public PluggableFileParser(XSSFWorkbook workbook, SheetParser[] sheetParsers, List<String> errors) {
		super();
		this.workbook = workbook;
		this.sheetParsers = sheetParsers;
		this.setErrors(errors);//TODO: 应当把 errors 改成 protected，这样就能 this.errors=errors;
							   //TODO：PluggableFileParser、sheetParser、rowParser、CellParser 都应当 设置 自己的 errors 属性 
		
		spreadErrorHook(errors);
	}
	
	/**
	 * 将 errors 传播到 各个 sheetValidator、rowValidator、cellValidator、cellExtractor
	 */
	public void spreadErrorHook(List<String> errors) {
		for (SheetParser sheetParser : sheetParsers) {
			sheetParser.spreadErrorHook(errors);
		}
	};

	public void parse() throws Exception {
		
		
		for (SheetParser sheetParser : sheetParsers) {
			
			//1、构建 XSSFSheet[] sheets
			String[] sheetNames = sheetParser.getSheetNames();
			
			List<XSSFSheet> sheetList = new ArrayList<XSSFSheet>();
//			XSSFSheet[] sheets = new XSSFSheet[sheetNames.length];
			
			for(int i=0; i<sheetNames.length; i++) {
				XSSFSheet sheet = workbook.getSheet(sheetNames[i]);
				
				if(sheet != null) {
					sheetList.add(sheet);
//					sheets[i] = sheet;
					
				}else {//如果没有这个 sheet
					
					logError(new NoSuchSheetException(workbook, sheetNames[i]));
					break;
				}
			}
			
			//2、将 sheets 交给  sheetParser
			XSSFSheet[] sheets = (XSSFSheet[]) sheetList.toArray(new XSSFSheet[0]);
			sheetParser.setSheets(sheets);
			
			//3、解析 sheetParser 中的  XSSFSheet[] sheets
			sheetParser.parse();
			
		}
	}
	
	public static void main(String[] args) throws IOException {

		File file = new File("bbb.xlsx");
		logger.debug(file.getAbsolutePath());
		
		
		FileInputStream fis = new FileInputStream(file);
		XSSFWorkbook xwb = new XSSFWorkbook(fis);
		
		XSSFSheet aa = xwb.getSheet("aaaa");//当 aaaa sheet 不存在时，并不会报错，而是 XSSFSheet aa=null
		logger.debug(aa);
	}

	public XSSFWorkbook getWorkbook() {
		return workbook;
	}

	public void setWorkbook(XSSFWorkbook workbook) {
		this.workbook = workbook;
	}

	public SheetParser[] getSheetParsers() {
		return sheetParsers;
	}

	public void setSheetParsers(SheetParser[] sheetParsers) {
		this.sheetParsers = sheetParsers;
	}
	
	
}
